package com.bxx.service.impl;

import com.alibaba.fastjson.JSON;
import com.bxx.dao.ScoreDao;
import com.bxx.dao.StudentExamAnswerDao;
import com.bxx.dao.StudentExamDao;
import com.bxx.pojo.Score;
import com.bxx.pojo.StudentExamAnswer;
import com.bxx.service.ScoreService;
import com.bxx.service.StudentExamAnswerService;
import com.bxx.util.PageUtil;
import com.bxx.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class ScoreServiceImpl implements ScoreService {

    //久层对象
    @Autowired
    private ScoreDao scoreDao;
    //redis缓存对象
    @Autowired
    StringRedisTemplate redisTemplate;
    //久层对象
    @Autowired
    private StudentExamAnswerDao StudentExamAnswerDao;
    //久层对象
    @Autowired
    private StudentExamDao studentExamDao;
    //保存总分
    double sum=0;
    @Override
    public PageUtil<Score> listScores(PageUtil<Score> pageUtil) {
        List<Score> scores = scoreDao.listScores(pageUtil);
        int count = scoreDao.listScoresCount(pageUtil);

        pageUtil.setData(scores);
        System.out.println("scores的长度="+scores.size());
        System.out.println("count==="+count);
        pageUtil.setCount(count);
        return pageUtil;

    }

    /**
     * 保存批改 ，修改分数表的状态和分数
     * @param score
     * @return
     */
    @Override
    public R Rewinding(Score score) {
       //在考生考生答案表中保存单题分数
        redisTemplate.boundHashOps(score.getStudentId() + score.getTestPaperId()).values().stream().map
           (v -> (String) v).map(StudentExamAnswerString -> JSON.parseObject(StudentExamAnswerString, StudentExamAnswer.class)).forEach(o1 -> {
             sum+= o1.getScore();
            StudentExamAnswerDao.updateStudentExamAnswer(o1);
            System.out.println("获取map中的value值" + o1);
        });
        score.setScore(sum);
        //修改考试状态
        studentExamDao.updateStautes(score.getStudentId());
         redisTemplate.delete(score.getStudentId() + score.getTestPaperId());
        //修改
        int r = scoreDao.updateScore(score);
        if(r>0){
            return R.ok("新增成功");
        }else {
            return R.error("新增失败");
        }



    }


}
